package org.peipito.prs;

import org.peipito.prs.engine.GameEngine;

import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;

public class MainThread extends Thread {

	// Surface holder that can access the physical surface
	private SurfaceHolder surfaceHolder;
	// The actual view that handles inputs
	// and draws to the surface
	private MainGamePanel gamePanel;
	private GameEngine engine;
	
	private static final String TAG = MainThread.class.getSimpleName();

	public MainThread(SurfaceHolder surfaceHolder, MainGamePanel gamePanel) {
		super();
		this.surfaceHolder = surfaceHolder;
		this.gamePanel = gamePanel;
		engine = new GameEngine();
		this.gamePanel.setEngine(engine);
	}
	
	@Override
	public void run(){
		
		Canvas canvas;
		Log.d(TAG, "Starting game loop");
		
		while ( running ){
			canvas = null;
			// try locking the canvas for exclusive pixel editing in the surface.
			
			try{
				canvas = this.surfaceHolder.lockCanvas();
//				this is not needed to update the engine here, as it is done from the Panel by the player.
				
				this.gamePanel.update();
				this.gamePanel.render(canvas);
				
			} finally {
				
				if(canvas != null){
					surfaceHolder.unlockCanvasAndPost(canvas);
				}
			}
		}
	}
	
	// flag to hold game state 
	private boolean running;
	public void setRunning(boolean running) {
		this.running = running;
	}
	
	
}
